package com.yanqu.road.server.manger.activity.gourdplant;

import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.gourdplant.*;
import com.yanqu.road.entity.enums.eActivityConfigType;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.logic.bussiness.activity.GourdPlantBussiness;
import com.yanqu.road.pb.activity.GourdPlantProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.gourdplant.GourdPlantModule;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class GourdPlantMgr extends TempMgr {

    public static int ACTIVITY_CHILD_TYPE = 2;

    static GourdPlantConfig config;

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    public static ActivityInfo getActivityInfo() {
        return config == null ? null : config.getActivityInfo();
    }

    public static void reloadActivityData() {
        getLogger().info("reload GourdPlant Activity start");
        ActivityInfo activityInfo;


        // 获取进行中的活动信息
        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.GourdChildActivity.getValue(), ACTIVITY_CHILD_TYPE);
        if (openActivityInfoList.isEmpty()) {
            getLogger().info("no GourdPlant Activity in show time");
            config = null;
            return;
        } else {
            activityInfo = openActivityInfoList.get(0);
        }

        GourdPlantConfig tmpConfig = new GourdPlantConfig();
        tmpConfig.setActivityInfo(activityInfo);
        int tmpActivityId = activityInfo.getActivityId();

        List<GourdPlantCombInfo> combList = GourdPlantBussiness.getGourdPlantCombInfoList(tmpActivityId);
        //固定比例的搭配，先确定需要排除的元素
        for (int i = 0; i < combList.size(); i++) {
            GourdPlantCombInfo comb = combList.get(i);
            if(comb.getElement().size() > 0 && comb.getSpecialElement().size() == 0){
                if(i + 1 < combList.size()){
                    GourdPlantCombInfo next = combList.get(i + 1);
                    if(next.getSpecialElement().size() > 0){
                        if(comb.getElement().get(0) == next.getSpecialElement().get(0).getNum()){
                            comb.getExcludeElement().add(next.getSpecialElement().get(0).getId());
                        }
                    }
                }
            }
            tmpConfig.getCombInfoMap().put(comb.getCombId(), comb);
        }
        tmpConfig.setCombInfoList(combList);

        List<GourdPlantItemInfo> itemList = GourdPlantBussiness.getGourdPlantItemInfoList(tmpActivityId);
        tmpConfig.setItemInfoList(itemList);

        // config配置
        Map<String, ActivityConfig> activityConfigMap = NormalActivityMgr.getActivityConfigMap(tmpActivityId);
        tmpConfig.setScoreItemId(activityConfigMap.get(eActivityConfigType.GOURD_PLANT_SCORE_ITEM_ID.getName()).getIntValue());
        tmpConfig.setUseItemId(activityConfigMap.get(eActivityConfigType.GOURD_PLANT_USE_ITEM_ID.getName()).getIntValue());
        tmpConfig.setExchangeItemId(activityConfigMap.get(eActivityConfigType.GOURD_PLANT_EXCHANGE_ITEM_ID.getName()).getIntValue());
        tmpConfig.setUserItemScore(activityConfigMap.get(eActivityConfigType.GOURD_PLANT_USE_ITEM_SCORE.getName()).getIntValue());
        if(activityConfigMap.containsKey(eActivityConfigType.GOURD_PLANT_USE_ITEM_REWARDS.getName())){
            String rewards = activityConfigMap.get(eActivityConfigType.GOURD_PLANT_USE_ITEM_REWARDS.getName()).getValue();
            tmpConfig.setUserItemRewards(rewards);
            List<String> rewardList = new ArrayList<>();
            List<Integer> rewardWeightList = new ArrayList<>();
            List<String> rewardItemList = StringUtils.stringToStringList(rewards, "\\|");
            for (String s : rewardItemList) {
                List<String> sList = StringUtils.stringToStringList(s, ";");
                rewardList.add(sList.get(0));
                rewardWeightList.add(Integer.valueOf(sList.get(1)));
            }
            tmpConfig.setUserItemRewardList(rewardList);
            tmpConfig.setUserItemRewardWeightList(rewardWeightList);
        }

        config = tmpConfig;

        getLogger().info("reload GourdPlant Activity finish");

        // 在线玩家下发数据
        for (GamePlayer gamePlayer : GamePlayerMgr.getAllOnlinePlayer()) {
            GourdPlantModule module = gamePlayer.getModule(GourdPlantModule.class);
            module.syncConfig();
            module.initUserData();
            module.syncUserData();
        }

    }


    /**
     * 随机组合
     */
    public static GourdPlantCombInfo randomComb(){
        if(config == null){
            return null;
        }
        Random random = new Random();
        List<Integer> weight = new ArrayList<>();
        for (GourdPlantCombInfo info : config.getCombInfoList()) {
            weight.add(info.getWeight());
        }
        int idx = RandomHelper.getRandomIndexByWeight(weight, random);
        if(idx == -1){
            return null;
        }
        return config.getCombInfoList().get(idx);
    }

    /**
     * 确定组合的具体元素
     */
    public static List<GourdPlantElement> getCombSpecialElement(GourdPlantCombInfo combInfo) {
        List<GourdPlantElement> result = new ArrayList<>();
        if (config == null) {
            return result;
        }
        //有固定元素的
        if (combInfo.getSpecialElement().size() > 0) {
            for (GourdPlantElement element : combInfo.getSpecialElement()) {
                result.add(element.clone());
            }
            return result;
        }
        //有固定比例的(6|1、5|2、5|1|1、4|3、4|2|1、4|1|1|1),无固定元素的
        if (combInfo.getElement().size() > 0 && combInfo.getSpecialElement().size() == 0) {
            List<Integer> excludeList = new ArrayList<>();
            for (int eId : combInfo.getExcludeElement()) {
                excludeList.add(eId);
            }
            List<Integer> poolList = getAllCombElementId(excludeList, config.getItemInfoList());
            Random random = new Random();
            for (int count : combInfo.getElement()) {
                int idx = random.nextInt(poolList.size());
                int id = poolList.remove(idx);
                result.add(new GourdPlantElement(id, count));
            }
            return result;
        }
        //其他不穷尽、固定比例x=2|y=2|n,n是其他5种，组合10(翻倍的话，增加随机性)个随机7-4=3个出来.(总组合个数是7)
        List<Integer> poolList = getAllCombElementId(new ArrayList<>(), config.getItemInfoList());
        int selectCount = 0;
        int[] countArr = new int[]{2, 2};
        Random random = new Random();
        for (int count : countArr) {
            int idx = random.nextInt(poolList.size());
            int id = poolList.remove(idx);
            result.add(new GourdPlantElement(id, count));
            selectCount += count;
        }
        //备选池翻倍
        List<Integer> tempList = new ArrayList<>();
        for (int seed : poolList) {
            tempList.add(seed);
        }
        poolList.addAll(tempList);
        int allCount = config.getItemInfoList().size();
        for(int i = selectCount; i < allCount; i++){
            int idx = random.nextInt(poolList.size());
            int id = poolList.remove(idx);
            result.add(new GourdPlantElement(id, 1));
        }
        return result;
    }

    /**
     * 组装备选池
     */
    public static List<Integer> getAllCombElementId(List<Integer> excludeList, List<GourdPlantItemInfo> itemInfoList){
        List<Integer> all = new ArrayList<>();
        for (GourdPlantItemInfo itemInfo : itemInfoList) {
            if(excludeList.contains(itemInfo.getId())){
                continue;
            }
            all.add(itemInfo.getId());
        }
        return all;
    }

    /**
     * 打乱顺序
     */
    public static List<Integer> upsetCombItem(List<GourdPlantElement> elementList) {
        List<GourdPlantElement> tempList = new ArrayList<>(elementList);
        List<Integer> itemList = new ArrayList<>();
        for (GourdPlantElement element : tempList) {
            for (int i = 0; i < element.getNum(); i++) {
                itemList.add(element.getId());
            }
        }
        List<Integer> result = new ArrayList<>();
        Random random = new Random();
        while (itemList.size() > 0){
            int idx = random.nextInt(itemList.size());
            int itemId = itemList.remove(idx);
            result.add(itemId);
        }
        return result;
    }


    public static GourdPlantConfig getConfig() {
        return config;
    }


    public static GourdPlantProto.GourdPlantUserDataSyncMsg.Builder parseUserDataSyncMsg(GourdPlantUserData data) {
        GourdPlantProto.GourdPlantUserDataSyncMsg.Builder builder = GourdPlantProto.GourdPlantUserDataSyncMsg.newBuilder();
        GourdPlantProto.GourdPlantUserDataTemp.Builder dataBuilder = getUserDataTempBuilder(data);
        builder.setUserData(dataBuilder);
        return builder;
    }

    public static GourdPlantProto.GourdPlantUserDataTemp.Builder getUserDataTempBuilder(GourdPlantUserData data) {
        GourdPlantProto.GourdPlantUserDataTemp.Builder dataBuilder = GourdPlantProto.GourdPlantUserDataTemp.newBuilder();
        dataBuilder.setScore(data.getScore());
        dataBuilder.setCombTimes(data.getCombTimes());
        if(data.getCombItems().size() > data.getCombTimes()) {
            dataBuilder.addAllCombItem(data.getCombItems().subList(0, data.getCombTimes()));
        }
        return dataBuilder;
    }
}
